package com.tueye.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tueye.base.util.Page;
import com.tueye.entity.SysDic;
import com.tueye.entity.SysDicValue;
import com.tueye.service.ISysDicService;
import com.tueye.utils.DateUtils;
import com.tueye.utils.UUIDGenerator;

/**
 * 系统字典控制器
 * @author hxw
 *
 */
@SuppressWarnings("unchecked")
@org.springframework.stereotype.Controller
@RequestMapping("/sysDic.do")
public class SysDicController extends BaseController {

	private static final Log log = LogFactory.getLog(SysDicController.class);
	
	@Autowired
	@Qualifier("sysDicService")
	private ISysDicService sysDicService;
	
	//@RequestMapping(method = { RequestMethod.POST })
	@RequestMapping(params = "action=PageShow")
	public String PageShow (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// js传过来的参数列表：
		// page:页数
		// rp:每页显示多少条
		// sortname：排序的字段名称
		// sortorder: 排序的方向；比如：asc，desc；
		// query : 查询的条件
		// qtype ：查询的类型
		
		String rp=request.getParameter("rp"); //每页显示的数据数
		String pageString=request.getParameter("page");//获取 flexgrid传过来的页数。
		String query=request.getParameter("query");//获取 查询的条件
		if(null != query)
		query = java.net.URLDecoder.decode(query , "UTF-8");//解码
		String error = request.getParameter("ss");
		//error.indexOf("23");
		String qtype=request.getParameter("qtype");//获取 查询的类型
		String sortorder=request.getParameter("sortorder");//获取 查询的类型
		if(pageString == null || pageString.length() == 0) {
			pageString = "1";
		}
		StringBuffer hql = new StringBuffer(" from com.tueye.entity.SysDic ");
		if(StringUtils.isNotEmpty(query)) hql.append(" where "+qtype+" ='"+query+"'");
		if(StringUtils.isNotEmpty(qtype))hql.append("   order   by "+qtype);
		if(StringUtils.isNotEmpty(sortorder))hql.append("   "+sortorder);
		
		Page pageModel = sysDicService.pagedQueryByHQL(hql.toString(), Integer.valueOf(pageString), Integer.valueOf(rp), null);
		
		Map pageInfo = new HashMap();
		pageInfo.put("page", new Integer(pageString));
		pageInfo.put("total", pageModel.getTotalCount());

		String jsonStr = getJsonString((ArrayList)pageModel.getResult(),pageInfo);
		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(jsonStr);
		
		return null;
	}
	
	
	
	
	@RequestMapping(params = "action=sysDicValue")
	public String sysDicValue (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// js传过来的参数列表：
		// page:页数
		// rp:每页显示多少条
		// sortname：排序的字段名称
		// sortorder: 排序的方向；比如：asc，desc；
		// query : 查询的条件
		// qtype ：查询的类型
		String id = request.getParameter("id");
		String rp=request.getParameter("rp"); //每页显示的数据数
		String pageString=request.getParameter("page");//获取 flexgrid传过来的页数。
		String query=request.getParameter("query");//获取 查询的条件
		if(null != query)
		query = java.net.URLDecoder.decode(query , "UTF-8");//解码
		String error = request.getParameter("ss");
		//error.indexOf("23");
		String qtype=request.getParameter("qtype");//获取 查询的类型
		String sortorder=request.getParameter("sortorder");//获取 查询的类型
		if(pageString == null || pageString.length() == 0) {
			pageString = "1";
		}
		StringBuffer hql = new StringBuffer(" from com.tueye.entity.SysDicValue ");
		if(StringUtils.isNotEmpty(query)) {
			hql.append(" where "+qtype+" ='"+query+"' and templateId ='"+id+"'");
		}else{
			hql.append(" where templateId ='"+id+"'");
		}
		
		if(StringUtils.isNotEmpty(qtype))hql.append("   order   by "+qtype);
		if(StringUtils.isNotEmpty(sortorder))hql.append("   "+sortorder);
		
		Page pageModel = sysDicService.pagedQueryByHQL(hql.toString(), Integer.valueOf(pageString), Integer.valueOf(rp), null);
		
		Map pageInfo = new HashMap();
		pageInfo.put("page", new Integer(pageString));
		pageInfo.put("total", pageModel.getTotalCount());

		String jsonStr = getSysDicValueJsonString((ArrayList)pageModel.getResult(),pageInfo);
		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(jsonStr);
		
		return null;
	}
	
	@RequestMapping(params = "action=standGridQuery")
	public String standGridQuery (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// js传过来的参数列表：
		// page:页数
		// rp:每页显示多少条
		// sortname：排序的字段名称
		// sortorder: 排序的方向；比如：asc，desc；
		// query : 查询的条件
		// qtype ：查询的类型
		
		String rp=request.getParameter("rp"); //每页显示的数据数
		String pageString=request.getParameter("page");//获取 flexgrid传过来的页数。
		String query=request.getParameter("query");//获取 查询的条件
		if(null != query)
		query = java.net.URLDecoder.decode(query , "UTF-8");//解码
		String qtype=request.getParameter("qtype");//获取 查询的类型
		String sortorder=request.getParameter("sortorder");//获取 查询的类型
		if(pageString == null || pageString.length() == 0) {
			pageString = "1";
		}
		StringBuffer hql = new StringBuffer(" from com.tueye.entity.SysDicValue ");
		if(StringUtils.isNotEmpty(query)) {
			hql.append(" where "+qtype+" ='"+query+"'");
		}
		
		if(StringUtils.isNotEmpty(qtype))hql.append("   order   by "+qtype);
		if(StringUtils.isNotEmpty(sortorder))hql.append("   "+sortorder);
		
		Page pageModel = sysDicService.pagedQueryByHQL(hql.toString(), Integer.valueOf(pageString), Integer.valueOf(rp), null);
		
		Map pageInfo = new HashMap();
		pageInfo.put("page", new Integer(pageString));
		pageInfo.put("total", pageModel.getTotalCount());

		String jsonStr = getSysDicValueJsonString((ArrayList)pageModel.getResult(),pageInfo);
		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(jsonStr);
		
		return null;
	}
	
	@RequestMapping(params = "action=save")
	public String save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		try {
			request.setCharacterEncoding("UTF-8");
			String mainId = (String) request.getParameter("id");
			String templateName = (String) request.getParameter("templateName");
			String templatePlate = request.getParameter("templatePlate");
			String templateDesc = request.getParameter("templateDesc");
			String templateEnlishName = request
					.getParameter("templateEnlishName");
			//新增
			if (StringUtils.isEmpty(mainId)) {
				SysDic sysDic = new SysDic();
				sysDic.setId(new UUIDGenerator().getUUID());
				sysDic.setTemplateName(templateName);
				sysDic.setTemplatePlate(templatePlate);
				sysDic.setTemplateDesc(templateDesc);
				sysDic.setSys_time(new Date());
				sysDic.setTemplateEnlishName(templateEnlishName);
				sysDicService.addSysDic(sysDic);
			} else {
				//修改
				SysDic sysDic = new SysDic();
				sysDic = sysDicService.getSysDicById(mainId);
				sysDic.setTemplateName(templateName);
				sysDic.setTemplatePlate(templatePlate);
				sysDic.setTemplateDesc(templateDesc);
				sysDic.setTemplateEnlishName(templateEnlishName);
				sysDic.setSys_time(new Date());
				sysDicService.addSysDic(sysDic);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(params = "action=saveModule")
	public String saveModule(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		try {
			request.setCharacterEncoding("UTF-8");
			String mainId = (String) request.getParameter("id");
			String templatePlate = request.getParameter("templatePlate");
			String moduleName = request.getParameter("moduleName");
			String modulePlate = request.getParameter("modulePlate");
			String moduleHtml = request.getParameter("moduleHtml");
			String templateId = request.getParameter("templateId");
			//新增
			if (StringUtils.isEmpty(mainId)) {
				SysDicValue sysDicValue = new SysDicValue();
				sysDicValue.setId(UUIDGenerator.getUUID());
				sysDicValue.setTemplateId(templateId);
				SysDic sysDic = sysDicService.getSysDicById(templateId);
				sysDicValue.setTemplateName(sysDic.getTemplateName());
				sysDicValue.setTemplatePlate(templatePlate);
				sysDicValue.setModulePlate(modulePlate);
				sysDicValue.setModuleName(moduleName);
				sysDicValue.setModuleHtml(moduleHtml);
				sysDicValue.setSys_time(new Date());
				sysDicService.addSysDicValue(sysDicValue);
			} else {
				SysDicValue sysDicValue = new SysDicValue();
				sysDicValue = sysDicService.getSysDicValueById(mainId);
				sysDicValue.setTemplateId(templateId);
				SysDic sysDic = sysDicService.getSysDicById(templateId);
				sysDicValue.setTemplateName(sysDic.getTemplateName());
				sysDicValue.setTemplatePlate(templatePlate);
				sysDicValue.setModulePlate(modulePlate);
				sysDicValue.setModuleName(moduleName);
				sysDicValue.setModuleHtml(moduleHtml);
				sysDicValue.setSys_time(new Date());
				sysDicService.addSysDicValue(sysDicValue);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 传递修改数据
	 */

	@RequestMapping(params = "action=editeSysDic")
	public String editeSysDic(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		try {
			request.setCharacterEncoding("UTF-8");
			String mainId = (String) request.getParameter("id");
			SysDic sysDic = new SysDic();
			//修改
			sysDic = sysDicService.getSysDicById(mainId);
			request.setAttribute("sysDic", sysDic);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/pages/admin/sysdic/addSysdic";
	}
	
	@RequestMapping(params = "action=editeSysDicValue")
	public String editeSysDicValue(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		try {
			request.setCharacterEncoding("UTF-8");
			String mainId = (String) request.getParameter("id");
			String templatePlate = request.getParameter("templatePlate");
			String templateId = request.getParameter("templateId");
			SysDicValue sysDicValue = sysDicService.getSysDicValueById(mainId);			
			request.setAttribute("sysDicValue", sysDicValue);
			request.setAttribute("templatePlate", templatePlate);
			request.setAttribute("templateId", templateId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/pages/admin/sysdic/addSysdicvalue";
	}
	
	
	@RequestMapping(params = "action=delete")
	public void delete (HttpServletRequest request, HttpServletResponse response){
		String retult = "true";
		try {
			request.setCharacterEncoding("UTF-8");
			String id = request.getParameter("id");
			sysDicService.delSysDic(id);
			String hql = " from com.tueye.entity.SysDicValue where templateId ='"+id+"'";
			sysDicService.delSysDicBySysDicValue(hql);
			response.getWriter().print("true");
		} catch (Exception e) {
			log.error("#####出错了"+e.getMessage());
			
		}
	}
	
	@RequestMapping(params = "action=deleteSysDicValue")
	public void deleteSysDicValue (HttpServletRequest request, HttpServletResponse response){
		String retult = "true";
		try {
			request.setCharacterEncoding("UTF-8");
			String id = request.getParameter("id");
			sysDicService.delSysDicValue(id);
			response.getWriter().print(retult);
		} catch (Exception e) {
			log.error("#####出错了"+e.getMessage());
			
		}
	}
	
	
	/**
	 * @param list
	 * @param pageInfo
	 * @return
	 */
	private String getJsonString(List list, Map pageInfo) {

		List mapList = new ArrayList();   
		for (int i = 0; i < list.size(); i++) {
			SysDic sysDic = (SysDic) list.get(i);
			Map cellMap = new HashMap();
			cellMap.put("numid", i+1);
			cellMap.put("model", "<a href='sysdicvalue.jsp?id="+sysDic.getId()+"&templateName="+sysDic.getTemplateName()
    				+"&templatePlate="+sysDic.getTemplatePlate()+"'>查看</a>");
    		cellMap.put("cell", new Object[]{
    				sysDic.getId(),
    				i+1,
    				sysDic.getTemplateName(),
    				sysDic.getTemplatePlate(),
    				sysDic.getTemplateDesc(),
    				DateUtils.getDate2Str("yyyy-MM-dd HH:mm",sysDic.getSys_time()),
    				"<a href='sysdicvalue.jsp?id="+sysDic.getId()+"&templateName="+sysDic.getTemplateName()
    				+"&templatePlate="+sysDic.getTemplatePlate()+"'>查看</a>"
    				});
    		  
    				mapList.add(cellMap);
    				
		}
		
    	pageInfo.put("rows", mapList);
    	com.tueye.ajax.json.JSONObject object = new com.tueye.ajax.json.JSONObject(pageInfo);
    	return object.toString();
	}
	
	private String getSysDicValueJsonString(List list, Map pageInfo) {

		List mapList = new ArrayList();   
		for (int i = 0; i < list.size(); i++) {
			SysDicValue sysDicValue = (SysDicValue) list.get(i);
			Map cellMap = new HashMap();
			cellMap.put("numid", i+1);
    		cellMap.put("cell", new Object[]{
    				sysDicValue.getId(),
    				i+1,
    				sysDicValue.getTemplateName(),
    				sysDicValue.getTemplatePlate(),
    				sysDicValue.getModuleName(),
    				sysDicValue.getModulePlate(),
    				sysDicValue.getModuleHtml(),
    				sysDicValue.getTemplateId(),
    				DateUtils.getDate2Str("yyyy-MM-dd HH:mm",sysDicValue.getSys_time())
    				});
    		  
    				mapList.add(cellMap);
    				
		}
		
    	pageInfo.put("rows", mapList);
    	com.tueye.ajax.json.JSONObject object = new com.tueye.ajax.json.JSONObject(pageInfo);
    	return object.toString();
	}
	/**
	 * 
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("unused")
	private Object getJsonString(Object obj){
		
		JSONObject json = JSONObject.fromObject(obj);
		return json;
	}
	
}
